package de.mrclrchtr.education.account.service

import de.mrclrchtr.education.account.dto.UserDto
import de.mrclrchtr.education.account.jooq.tables.pojos.Role
import de.mrclrchtr.education.account.jooq.tables.pojos.User
import de.mrclrchtr.education.account.jooq.tables.references.ROLE_USER
import de.mrclrchtr.education.account.jooq.tables.references.USER
import org.jooq.DSLContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class UserService(@Autowired private val dslContext: DSLContext, @Autowired private val roleService: RoleService) {
    /**
     * 获取所有用户数据
     */
    fun getAllUsers(): MutableList<UserDto> {
        val mutableList = mutableListOf<UserDto>()
        val userMap = mutableMapOf<User, UserDto>()
        try {
            dslContext.select().from(USER)
                .leftJoin(ROLE_USER).on(USER.ID.eq(ROLE_USER.USER_ID))
                .fetch().forEach {
                    var roleList: MutableList<Role> = mutableListOf()
                    if (it.getValue(ROLE_USER.ROLE_ID) != null) {
                        roleList = roleService.getRolesById(it.getValue(ROLE_USER.ROLE_ID))
                    }
                    val userId = it.getValue(USER.ID)
                    val userName = it.getValue(USER.NAME)
                    val age = it.getValue(USER.AGE)

                    val user = User(userId, userName, age)
//                    if (userMap.containsKey(user)) {
//                        userMap[user]?.roleList?.addAll()
//                    } else {
//                        userMap[user] = UserDto.convertToCustomRole(user, roleList)
//                    }
                    val newUser = userMap[user]?.copy(
                        roleList = userMap[user]?.roleList?.toMutableList()?.apply { addAll(roleList) })
                        ?: UserDto.convertToCustomRole(user, roleList)
                    userMap[user] = newUser

                }
            // 将结果从map转换回list
            mutableList.addAll(userMap.values)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mutableList
    }

    /**
     *  根据id获取用户，并加上角色list
     */
    fun getUserByIdWithRoles(id: Int?): UserDto? {
        return try {
            val userRecord = dslContext.selectFrom(USER)
                .where(USER.ID.eq(id))
                .fetchOne()

            userRecord?.let { user ->
                val userId = user[USER.ID]
                val userName = user[USER.NAME]
                val age = user[USER.AGE]

                // 查询与该用户关联的角色ID
                val roleUserRecords = dslContext.select(ROLE_USER.ROLE_ID)
                    .from(ROLE_USER)
                    .where(ROLE_USER.USER_ID.eq(userId))
                    .fetch()

                val roleList = roleUserRecords.mapNotNull { roleService.getRolesById(it[ROLE_USER.ROLE_ID]) }.flatten()
                    .toMutableList()
                UserDto.convertToCustomRole(User(userId, userName, age), roleList)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }

    }


    /**
     * 根据id获取用户
     */
    fun getUsersById(id: Int?): MutableList<User> {
        var mutableList = MutableList(0) { User(0, "", 0) }
        dslContext.select().from(USER).where(USER.ID.eq(id)).fetch().forEach {
            mutableList.add(User(it.getValue(USER.ID), it.getValue(USER.NAME), it.getValue(USER.AGE)))
        }
        return mutableList
    }

    /**
     * 修改用户
     */
    fun updateUser(user: User, roleIds: List<Int>): String {
        if (user.id == null || roleIds.isEmpty())
            return "无效的参数，无法更新"
        dslContext.update(USER).set(USER.NAME, user.name)
            .set(USER.AGE, user.age).where(USER.ID.eq(user.id))
            .execute()


        //获取当前关联的角色id
        val existingRolesId = dslContext.select(ROLE_USER.ROLE_ID).from(ROLE_USER).where(ROLE_USER.USER_ID.eq(user.id))
            .fetchInto(Int::class.java)

        //计算要删除的用户id
        val toDeleteRoleIds = existingRolesId.minus(roleIds)
        if (toDeleteRoleIds.isNotEmpty()) {
            dslContext.deleteFrom(ROLE_USER).where(ROLE_USER.USER_ID.eq(user.id))
                .and(ROLE_USER.ROLE_ID.`in`(toDeleteRoleIds)).execute()
        }
        //计算出需要插入的用户id
        val toAddRoleIds = roleIds.minus(existingRolesId)
        if (toAddRoleIds.isNotEmpty()) {
            toAddRoleIds.forEach { roleId ->
                dslContext.insertInto(ROLE_USER)
                    .columns(ROLE_USER.USER_ID, ROLE_USER.ROLE_ID)
                    .values(user.id, roleId)
                    .execute()
            }
        }
        return "更新成功"
    }

    /**
     * 根据id删除用户
     */
    fun deleteUserById(id: Int?): String {
        if (id == null)
            return "无效的参数，无法删除"
        val execute1 = dslContext.deleteFrom(USER).where(USER.ID.eq(id)).execute()
        val execute2 = dslContext.deleteFrom(ROLE_USER).where(ROLE_USER.USER_ID.eq(id)).execute()
        return if (execute1 > 0 || execute2 > 0) "删除成功" else "删除失败"
    }

    /**
     * 新增用户
     */
    fun addUser(user: User): String {
//        println(user)
        if (user.id != null)
            return "无效的参数，无法新增"
        val execute = dslContext.insertInto(USER).set(USER.NAME, user.name)
            .set(USER.AGE, user.age).execute()
        return if (execute > 0) "新增成功" else "新增失败"

    }

}